import React, { useState, useRef } from 'react';
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Radio, Popconfirm, Tooltip, Select } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import RcViewer from '@hanyk/rc-viewer';
import { useLatest } from 'ahooks';

var storage = window.localStorage;

/**
 *  @param {boolean} showCz  是否显示操作区
 * @param {function} handleEdit  编辑的回调方法
 * @param {function} handleDelete  删除的回调方法
 * @param {boolean} rowSelection  是否显示行选择 
 * @returns */
const Custom_table_hooks_config = (props) => {

  const history = useHistory();
  const [selectionType, setSelectionType] = useState(props.selecttype ? props.selecttype : 'checkbox');
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [currentdatas, setcurrentdatas] = useState([])
  const [isExactMatch, setIsExactMatch] = useState(false);
  const isExactMatchRef = useLatest(isExactMatch);
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: props.selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      props.handleselectson(selectedRows, selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(false);
  };

  const handleSearchExact = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(true);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        if (props.sfdoubleclick) {
          storage[props.storagekey] = JSON.stringify(record)
          history.push({ pathname: props.doubleclickroute });
        } else;
      }
    }
  };

  //改为下拉框搜索模式
  const getColumnSearchProps = (dataIndex, style, rendertype, ifcolor, title, searchtype,item) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 16,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        {
          //根据类型选择input、select或list列表模式
          searchtype == "select" ?
            <Select
              ref={searchInput}
              mode="multiple"
              showSearch
              placeholder={`搜索${title}`}
              onChange={(value) => setSelectedKeys(value)}
              onSearch={(value) => setSelectedKeys(value ? [value] : [])}
              onClear={() => {
                setSelectedKeys([]);
                clearFilters();
              }}
              allowClear
              style={{
                width: '20vw',
                marginBottom: 8,
                display: 'block',
              }}
            >
              {[...new Set(props.tabledata.map(item => item[dataIndex]))].map((value) => (
                <Select.Option key={value} value={value}>
                  {value}
                </Select.Option>
              ))}
            </Select>
            :
            <Input
              ref={searchInput}
              placeholder={`搜索${title}`}
              value={selectedKeys[0]}
              onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
              style={{
                marginBottom: 8,
                display: 'block',
              }}
            />
        }
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
          <Button
            type="primary"
            onClick={() => handleSearchExact(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            精准搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      searchtype == "select" ?
        <FilterOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
        :
        <SearchOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
    ),
    onFilter: (value, record) => {
      if (searchtype == "select") {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      } else if (isExactMatchRef.current) {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      } else {
        return record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
      }
    },
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) => {
      const renderContent = (text, rendertype) => {
        // 处理图片渲染
        if (rendertype === "img") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无图片</span>
              </div>
            );
          }
          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black", display: "flex", flexDirection: "row" }}>
              <RcViewer options={{ toolbar: 1 }}>
                {text.split(',').map((item, index) => (
                  <div key={index} style={{ width: "4vw", height: "4vw", position: 'relative', marginLeft: "0.1vw", display: "inline-block" }}>
                    <img
                      style={{ width: "90%", left: "0", position: "absolute", right: "0", top: "0", bottom: "0", margin: "auto" }}
                      src={`http://111.77.154.58:2233/${item}`}
                      alt=""
                    />
                  </div>
                ))}
              </RcViewer>
            </div>
          );
        }
        // 处理URL渲染
        if (rendertype === "url") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无附件</span>
              </div>
            );
          }
          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
              {text.split(',').map((item, index) => (
                <div key={index} style={{ position: 'relative' }}>
                  <a
                    style={{ color: "#0885fb" }}
                    href={`http://111.77.154.58:2233/${item}`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    附件{index + 1}
                  </a>
                </div>
              ))}
            </div>
          );
        }
        if (rendertype == "tooltips") {
          return (
            <span style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
              <Tooltip title={text}>
                <span style={style ? style : {}}>{props.supplierMap[text]}</span>
              </Tooltip>
            </span>
          )
        }
        if (rendertype == "tooltip") {
          return (
            <span style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={style ? style : {}}>{text==storage.ygxm?"本公司":props.supplierMap[text]}</span>
            </span>
          )
        }
        // 处理普通文本渲染
        if (searchedColumn === dataIndex) {
          return (
            <Highlighter
              highlightStyle={{
                backgroundColor: '#ffc069',
                padding: 0,
              }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          );
        }
        return (
          <span style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
            <span style={style ? style : {}}>{text}</span>
          </span>
        );
      };
      return renderContent(text, rendertype);
    },
  });

  const colnumsorigin = props.tablecolnum.filter(item => item.show == true)

  const columns = colnumsorigin.map(item => {
    if (props.ifsort) {
      return {
        title: item.title,
        dataIndex: item.key,
        key: item.key,
        ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),
        sorter: (a, b) => a[item.key] > b[item.key],
        width: item.width ? item.width : false,
        fixed: item.fixed ? item.fixed : false,
        sortDirections: ['descend', 'ascend'],
      }
    } else if (props.noSearch) {
      return {
        title: item.title,
        dataIndex: item.key,
        key: item.key,
        width: item.width ? item.width : false,
        fixed: item.fixed ? item.fixed : false,
      }
    } else {
      return {
        title: item.title,
        dataIndex: item.key,
        key: item.key,
        width: item.width ? item.width : false,
        fixed: item.fixed ? item.fixed : false,
        ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),
      }
    }
  })
  props.showCz ?
    columns.push({
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: props.czWidth ? props.czWidth : "100px",
      render: (text, record) => (
        props.renderCz ? props.renderCz(record) :
          <Space style={{ width: "80px" }}>
            {props.showCz.showEdit && <Popconfirm title="编辑单据?" onConfirm={() => props.handleEdit(record, "edit")}>
              <Button style={{ fontSize: '0.6rem', backgroundColor: "#f0fdfd", fontWeight: "600", color: "#090c94" }} size="small" ><EditOutlined />编辑</Button>
            </Popconfirm>}
            {props.showCz.showView && <Popconfirm title="查看单据?" onConfirm={() => props.handleEdit(record, "view")}>
              <Button style={{ fontSize: '0.6rem', backgroundColor: "#ffffff", fontWeight: "500", color: "#666666" }} size="small" ><EyeOutlined />查看</Button>
            </Popconfirm>}
            {props.showCz.showDelete && <Popconfirm title="删除单据?" onConfirm={() => props.handleDelete(record)}>
              <Button style={{ fontSize: '0.6rem', backgroundColor: "#fce8e8", fontWeight: "800", color: "#a91f24" }} size="small"><DeleteOutlined />删除</Button>
            </Popconfirm>}
          </Space>
      )
    }) : ''

  return (
    <div style={{ position: "relative", height: "", width: props.width ? props.width : "100%" }}>
      <Radio.Group style={{ display: props.ifhiddencchangeselecttype ? "none" : "block" }}
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
        <Radio value="checkbox">多选</Radio>
        <Radio value="radio">单选</Radio>
      </Radio.Group>
      {
        props.title ? (<Table columns={columns} dataSource={props.tabledata} style={{
          width: "98%", minHeight: "20vh", marginRight: "1%"
        }}
          title={() => { return <div style={{ fontWeight: "800" }}>{props.title}</div> }}
          size="small"
          pagination={{
            defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 20
            , total: props.tabledata.length, pageSizeOptions: ['15', '30', '50', '110'], position: ['bottomLeft']
          }}
          bordered={props.bordered ? props.bordered : false}
          onRow={onRowSelect}
          scroll={props.scroll ? props.scroll : false}
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }} />)
          :
          (<Table columns={columns} dataSource={props.tabledata} style={{
            width: "98%", marginRight: "1%", marginLeft: "1%"
          }}
            size="small"
            pagination={{
              defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 20,
              total: props.tabledata.length, pageSizeOptions: ['15', '30', '50', '110', '200', '500'],
              position: ['bottomLeft']
            }}
            bordered={props.bordered ? props.bordered : false}
            scroll={props.scroll ? props.scroll : false}
            onChange={(pagination, filters, sorter, extra) => {
              setcurrentdatas(extra.currentDataSource)
            }}
            rowClassName={props.rowClassName ? (record, index) => { return props.rowClassName(record, index) } : ''}
            onRow={onRowSelect}
            {...props.rowSelection ? '' : {
              rowSelection: {
                type: selectionType,
                ...rowSelection,
              }
            }}
            />)
      }
    </div>)
}

export default Custom_table_hooks_config